package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.JsonResult;
import cn.wolfcode.domain.LoginCheck;
import cn.wolfcode.exception.LogicException;
import cn.wolfcode.exception.LogicOverException;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@Controller
public class LoginController {
    static{

    }
    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private IPermissionService permissionService;

    private Integer countLogin = 0;

    //登录判断,登录成功后存到session中
    @RequestMapping("/userlogin")
    @ResponseBody //用于返回JSON格式数据,会把JsonResult的Java对象自动转为JSON返回给视图
    public JsonResult login(String username, String password, HttpSession session) {
        //判断登录次数,超过5次则一分钟内不能登陆
        LoginCheck loginCheck1 = (LoginCheck)session.getAttribute("loginCheck");
        if(loginCheck1 != null){
            long timeLogin = loginCheck1.getLoginTime().getTime();
            long nowTime = new Date().getTime();
            long checkTime = nowTime - timeLogin;

            if(loginCheck1.getCount() >= 5 && checkTime <= 60000){
                throw new LogicException("错误过多,请一分钟后再试");
            }else if(loginCheck1.getCount() >= 5 && checkTime > 60000){
                countLogin = 0;
                session.invalidate();
            }
        }

        try {
            Employee employee = employeeService.checkLogin(username, password);
            //把用户信息存到session
            UserContext.setCurrentUser(employee);

            //顺便把该用户的所有权限集合都保存再session中,这样可以节省SQL语句查询
            //需要先判断是否为管理员
            if (!employee.isAdmin()) {
                List<String> stringList = permissionService.queryExpByEid(employee.getId());
                UserContext.setPermissions(stringList);
            }
            return new JsonResult();//默认为true
        } catch (LogicOverException loe) {
            this.countLogin++;
            LoginCheck loginCheck = new LoginCheck(this.countLogin,new Date());
            session.setAttribute("loginCheck", loginCheck);
            throw new LogicException("用户名或者密码错误");
        }
    }

    //注销功能
    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        //session.removeAttribute("USER_IN_SESSION");
        //可以直接销毁会话本身,包括用户权限
        session.invalidate();
        return "redirect:/login.html";
    }

    //无权限页面
    @RequestMapping("/nopermission")
    public String noPermission() {
        return "common/nopermission";
    }
}
